const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const { getBookInfoByISBN } = require('../services/bookDataService');

/**
 * Excel批量导入图书控制器
 */

/**
 * 批量导入图书（基础信息）
 */
exports.batchImportBooks = async (req, res, next) => {
  try {
    const { books } = req.body; // books是一个数组

    if (!Array.isArray(books) || books.length === 0) {
      return error(res, '请提供有效的图书列表', 400);
    }

    if (books.length > 500) {
      return error(res, '单次最多导入500本图书', 400);
    }

    const results = {
      success: [],
      failed: [],
      duplicates: []
    };

    for (const book of books) {
      try {
        const { isbn, name, author, publisher, category, stock } = book;

        // 验证必填字段
        if (!name) {
          results.failed.push({
            book: book,
            reason: '图书名称不能为空'
          });
          continue;
        }

        // 检查ISBN是否已存在（如果提供了ISBN）
        if (isbn) {
          const [existing] = await pool.query(
            'SELECT id, name FROM books WHERE isbn = ?',
            [isbn]
          );

          if (existing.length > 0) {
            results.duplicates.push({
              isbn,
              name,
              existing_name: existing[0].name,
              reason: 'ISBN已存在'
            });
            continue;
          }
        }

        // 插入图书
        const [result] = await pool.query(`
          INSERT INTO books (isbn, name, author, publisher, category, stock)
          VALUES (?, ?, ?, ?, ?, ?)
        `, [
          isbn || null,
          name,
          author || '未知作者',
          publisher || '未知出版社',
          category || '其他',
          stock || 1
        ]);

        results.success.push({
          id: result.insertId,
          name,
          isbn: isbn || '无'
        });

      } catch (err) {
        results.failed.push({
          book: book,
          reason: err.message
        });
      }
    }

    success(res, {
      total: books.length,
      success_count: results.success.length,
      failed_count: results.failed.length,
      duplicate_count: results.duplicates.length,
      details: results
    }, `批量导入完成：成功${results.success.length}本，失败${results.failed.length}本，重复${results.duplicates.length}本`);

  } catch (err) {
    next(err);
  }
};

/**
 * 通过ISBN批量查询图书（本地数据库）
 * 前端提供ISBN列表，后端在数据库中查询
 */
exports.batchFetchByISBN = async (req, res, next) => {
  try {
    const { isbns } = req.body;

    if (!Array.isArray(isbns) || isbns.length === 0) {
      return error(res, '请提供有效的ISBN列表', 400);
    }

    const results = {
      found: [],
      notFound: []
    };

    for (const isbn of isbns) {
      try {
        const [books] = await pool.query(
          'SELECT * FROM books WHERE isbn = ? LIMIT 1',
          [isbn]
        );

        if (books.length > 0) {
          results.found.push({
            isbn: isbn,
            book: books[0]
          });
        } else {
          results.notFound.push({
            isbn: isbn,
            reason: '本地数据库中未找到'
          });
        }
      } catch (err) {
        results.notFound.push({
          isbn: isbn,
          reason: err.message
        });
      }
    }

    success(res, {
      total: isbns.length,
      found_count: results.found.length,
      not_found_count: results.notFound.length,
      results: results
    }, `批量查询完成：找到${results.found.length}个，未找到${results.notFound.length}个`);

  } catch (err) {
    next(err);
  }
};

/**
 * 批量导入图书（传统方式：手动提供完整信息）
 * 注：不再自动从外部API获取信息
 */
exports.batchImportWithISBN = async (req, res, next) => {
  try {
    const { books } = req.body; // 改为接收完整的图书信息数组

    if (!Array.isArray(books) || books.length === 0) {
      return error(res, '请提供有效的图书列表', 400);
    }

    if (books.length > 100) {
      return error(res, '单次最多导入100本图书', 400);
    }

    const results = {
      success: [],
      failed: [],
      duplicates: []
    };

    for (const book of books) {
      try {
        const { isbn, name, author, publisher, category, stock } = book;

        if (!name) {
          results.failed.push({
            book: book,
            reason: '图书名称不能为空'
          });
          continue;
        }

        // 检查ISBN是否已存在
        if (isbn) {
          const [existing] = await pool.query(
            'SELECT id, name FROM books WHERE isbn = ?',
            [isbn]
          );

          if (existing.length > 0) {
            results.duplicates.push({
              isbn,
              name,
              existing_name: existing[0].name,
              reason: 'ISBN已存在'
            });
            continue;
          }
        }

        // 插入数据库
        const [result] = await pool.query(`
          INSERT INTO books 
          (isbn, name, author, publisher, category, stock, data_source)
          VALUES (?, ?, ?, ?, ?, ?, ?)
        `, [
          isbn || null,
          name,
          author || '未知作者',
          publisher || '未知出版社',
          category || '未分类',
          stock || 1,
          'manual' // 标记为手动录入
        ]);

        results.success.push({
          isbn: isbn || '无',
          id: result.insertId,
          name: name
        });

      } catch (err) {
        results.failed.push({
          book: book,
          reason: err.message
        });
      }
    }

    success(res, {
      total: books.length,
      success_count: results.success.length,
      failed_count: results.failed.length,
      duplicate_count: results.duplicates.length,
      details: results
    }, `批量导入完成：成功${results.success.length}本，失败${results.failed.length}本，重复${results.duplicates.length}本`);

  } catch (err) {
    next(err);
  }
};

/**
 * 获取导入进度（用于前端轮询）
 */
let importProgress = {
  isImporting: false,
  total: 0,
  current: 0,
  status: 'idle' // idle, importing, completed, error
};

exports.getImportProgress = (req, res, next) => {
  success(res, importProgress);
};

